<!--
 * @Description: 我的订单页面组件
 * @Author: hai-27
 * @Date: 2020-02-20 17:21:54
 * @LastEditors: hai-27
 * @LastEditTime: 2020-02-27 13:36:27
 -->
<template>
  <div class="order">
    <!-- 我的订单头部 -->
    <div class="order-header">
      <div class="order-header-content">
        <p>
          <i class="el-icon-s-order" style="font-size: 30px;color: #ff6700;"></i>
          我的订单
        </p>
      </div>
    </div>
    <!-- 我的订单头部END -->

    <!-- 我的订单主要内容 -->
    <div class="order-content" v-if="orders.length>0">
      <div class="content" v-for="(item,index) in orders" :key="index">
        <ul>
          <!-- 我的订单表头    -->
          <li class="order-info">
            <div class="order-id">订单编号: {{ item[0].orderID }}</div>
            <div class="order-time">订单时间: {{ item[0].createdTime | dateFormat }}</div>
          </li>
          <li class="header">
            <div class="pro-img"></div>
            <div class="pro-name">商品名称</div>
            <div class="pro-price">单价</div>
            <div class="pro-num">数量</div>
            <div class="pro-total">小计</div>
            <div class="pro-status">支付状态</div>
            <div class="pro-delete">删除订单</div>
          </li>
          <!-- 我的订单表头END -->

          <!-- 订单列表 -->
          <li class="product-list" v-for="product in item" :key="product.productID">
            <div class="pro-img">
              <router-link :to="{ path: '/goods/details', query: {productID:product.productID} }">
                <img :src="product.productImg"/>
              </router-link>
            </div>
            <div class="pro-name">
              <router-link
                  :to="{ path: '/goods/details', query: {productID:product.productID} }"
              >{{ product.productName }}
              </router-link>
            </div>
            <div class="pro-price">{{ product.productPrice }}元</div>
            <div class="pro-num">{{ product.productNum }}</div>
            <div class="pro-total pro-total-in">{{ product.productPrice * product.productNum }}元</div>

            <!-- 支付状态 -->
            <div class="pro-status">
              <div v-if="product.payStatus==='待支付'">
                <a href="javascript:;"
                   @click="goToPay(product.orderID,product.productPrice*product.productNum,product.payStatus)">{{ product.payStatus }}</a>
              </div>
              <div v-else-if="product.payStatus ==='待发货'|| product.payStatus ==='已完成'">
                <span>{{ product.payStatus }}</span>
              </div>
              <div v-else-if="product.payStatus==='待收货'">
                <a href="javascript:;" @click="confirmReceive(product.orderID,product.payStatus)">{{ product.payStatus }}</a>
              </div>
              <div v-else-if="product.payStatus==='待评价'">
                <a href="javascript:;" @click="alertInfo(product.payStatus)">{{ product.payStatus }}</a>
              </div>
            </div>
            <!-- 删除订单商品 -->
            <div class="pro-delete">
              <i class="el-icon-delete-solid" :style="{fontSize:'25px',}"
                 @click="deleteProduct(product.orderID,product.productID)"></i>
            </div>
          </li>
        </ul>
        <div class="order-bar">
          <div class="order-bar-left">
            <span class="order-total">
              共
              <span class="order-total-num">{{ total[index].totalNum }}</span> 件商品
            </span>
          </div>
          <div class="order-bar-right">
            <span>
              <span class="total-price-title">合计：</span>
              <span class="total-price">{{ total[index].totalPrice }}元</span>
            </span>
          </div>
          <!-- 订单列表END -->
        </div>
      </div>
      <div style="margin-top:-40px;"></div>
    </div>
    <!-- 我的订单主要内容END -->

    <!-- 订单为空的时候显示的内容 -->
    <div v-else class="order-empty">
      <div class="empty">
        <h2>您的订单还是空的！</h2>
        <p>快去购物吧！</p>
      </div>
    </div>
    <!-- 订单为空的时候显示的内容END @current-change="currentChange"  -->
    <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="pageSize"
          :total="total1"
          @current-change="currentChange">
        </el-pagination>
      </div>

    

  </div>
</template>
<script>
export default {
  data() {
    return {
      orders: [
        [{
          createdTime: "2022-05-18T14:14:37.833512",
          orderID: "202205181414373940795",
          payStatus: "待支付",
          productID: 1,
          productImg: "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/18d2099cb0b05bbd23cb1915dfc9d0d6.jpg?thumb=1&w=400&h=400&f=webp&q=90",
          productName: "Redmi K30",
          productNum: 1,
          productPrice: 1599
        }],
        [{
          createdTime: "2022-05-10T08:50:21.602281",
          orderID: "202205100850213916878",
          payStatus: "待发货",
          productID: 2,
          productImg: "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/28c14106b688ac7ae88e761564789b37.jpg?thumb=1&w=400&h=400&f=webp&q=90",
          productName: "Redmi K30 5G",
          productNum: 1,
          productPrice: 2599
        },
          {
            createdTime: "2022-05-10T08:50:21.602281",
            orderID: "202205100850213916878",
            payStatus: "待发货",
            productID: 1,
            productImg: "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/18d2099cb0b05bbd23cb1915dfc9d0d6.jpg?thumb=1&w=400&h=400&f=webp&q=90",
            productName: "Redmi K30",
            productNum: 1,
            productPrice: 1599
          }
        ]
      ], // 订单列表
      total: [], // 每个订单的商品数量及总价 列表
      pageSize:2, // 每页展示的商品数量
      currentPage:1, // 当前页码
      total1: 0, // 商品总量
    };
  },


  activated() {
    // 下两行代码临时使用，为了使 watch 里面的方法执行
    this.orders.push([])
    this.orders.pop()

    // TODO 加载订单数据
    this.$axios.get('/orders/user/order/',{
      params:{
        pageSize:this.pageSize,
        currentPage:this.currentPage,
      },
      headers:{
        Authorization:localStorage.token || ''
      }
    })
    .then(res => {
      console.log('加载订单的响应',res)
      if(res.data.code == 200){
        this.orders = res.data.orders
        this.total1 = res.data.total1
      }else{
        // this.notifError(res.data.msg)
      }
    })
    .catch(err => {
      return Promise.reject(err)
    })

  },

  methods: {

    // 返回顶部
    backtop() {
      const timer = setInterval(function () {
        const top = document.documentElement.scrollTop || document.body.scrollTop;
        const speed = Math.floor(-top / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
            top + speed;

        if (top === 0) {
          clearInterval(timer);
        }
      }, 20);
    },

    // 页码变化调用currentChange方法
    currentChange(currentPage) {
      this.currentPage = currentPage;
      this.$axios.get('/orders/user/order/',{
      params:{
        pageSize:this.pageSize,
        currentPage:this.currentPage,
      },
      headers:{
        Authorization:localStorage.token || ''
      }
    })
    .then(res => {
      console.log('加载订单的响应',res)
      if(res.data.code == 200){
        this.orders = res.data.orders
        this.total1 = res.data.total1
      }else{
        // this.notifError(res.data.msg)
      }
    })
    .catch(err => {
      return Promise.reject(err)
    })

      // alert(currentPage)
    },

    alertInfo(val) {
      this.notifySucceed(val)
    },

    // 去支付
    goToPay(orderID,totalAmount,payStatus) {
      // TODO 未支付订单去支付
      console.log("订单ID", orderID,payStatus,totalAmount)
      // 生成订单的地址
      this.$axios.put('/orders/user/order/',{
        label: payStatus,
        orderID,
        totalAmount,

      })
      .then(res => {
        console.log('点击支付的响应',res)
      // 处理响应
      if(res.data.code == 200){
        // 重定向到支付地址
        this.notifySucceed(res.data.msg)
        // 一次性定时器,2秒后触发
        setTimeout(window.location.href=res.data.pay_url,2000)
      }else{
        // this.notifError(res.data.msg)
      }
      })
      .catch(err => {
        return Promise.reject(err)
      })






    },
    // 删除订单商品
    deleteProduct(orderID, productID) {

      let r = confirm("确定删除？")
      if (r) {
        // TODO 删除订单
        console.log("删除订单，订单号：", orderID, "订单商品", productID)
        this.$axios.delete('/orders/user/order/',{
          data:{
            orderID,
            productID,
          }
        })
        .then(res => {
          console.log('删除订单商品的响应',res)
          // 待实现
          if(res.data.code == 200){
            for(let i=0;i<this.orders.length;i++){
              const orderArr = this.orders[i]
              if(orderArr.length == 1){
                let productobj = orderArr[0]
                if(productobj.productID == productID && productobj.orderID == orderID){
                  // 删除一个订单
                  this.orders.splice(i,1)
                }
              }else{
                for(let j=0;j<orderArr.length;j++){
                  const productobj = orderArr[j]
                  if(productobj.productID == productID && productobj.orderID == orderID){
                    orderArr.splice(j,1)
                  }
                }
              }
            }
          }

        })
        .catch(err => {
          return Promise.reject(err)
        })
      }
    },
    // 模拟确认收货
    confirmReceive(orderID,payStatus) {
      // 确认是否收货
      let r = confirm("确认收货？请谨慎操作")
      if (r) {
        // TODO 确认收货
        console.log("确认收货，订单ID", orderID,payStatus)

        this.$axios.put('/orders/user/order/',{
          label:payStatus,
          orderID,
        })
        .then(res => {
          console.log('确认收货的响应',res)
          if(res.data.code == 200){
            // 遍历数组 订单更新状态
            for(let i=0 ; i<this.orders.length;i++){
              const orderArr = this.orders[i]
              if(orderArr[0].orderID == orderID){
                // 找到确认的订单
                for(let j=0;j<orderArr.length;j++){
                  orderArr[j].payStatus = '待评价'
                }
              }
            }
          }else{
            // this.notifError(res.data.msg)
          }
        })
        .catch(err => {
          console.log('失败的响应',err)
          return Promise.reject(err)
        })
      }
    },
  },
  watch: {
    // 通过订单信息，计算出每个订单的商品数量及总价
    orders: function (val) {
      let total = [];
      for (let i = 0; i < val.length; i++) {
        const element = val[i];

        let totalNum = 0;
        let totalPrice = 0;
        for (let j = 0; j < element.length; j++) {
          const temp = element[j];
          totalNum += temp.productNum;
          totalPrice += temp.productPrice * temp.productNum;
        }
        total.push({totalNum, totalPrice});
      }
      this.total = total;
    },



  }
};
</script>
<style scoped>
.order {
  background-color: #f5f5f5;
  padding-bottom: 20px;
}

/* 我的订单头部CSS */
.order .order-header {
  height: 64px;
  border-bottom: 2px solid #ff6700;
  background-color: #fff;
  margin-bottom: 20px;
}

.order .order-header .order-header-content {
  width: 1225px;
  margin: 0 auto;
}

.order .order-header p {
  font-size: 28px;
  line-height: 58px;
  float: left;
  font-weight: normal;
  color: #424242;
}

/* 我的订单头部CSS END */
.order .content {
  width: 1225px;
  margin: 0 auto;
  background-color: #fff;
  margin-bottom: 50px;
}

.order .content ul {
  background-color: #fff;
  color: #424242;
  line-height: 85px;
}

/* 我的订单表头CSS */
.order .content ul .order-info {
  height: 60px;
  line-height: 60px;
  padding: 0 26px;
  color: #424242;
  border-bottom: 1px solid #ff6700;
}

.order .content ul .order-info .order-id {
  float: left;
  color: #ff6700;
}

.order .content ul .order-info .order-time {
  float: right;
}

.order .content ul .header {
  height: 85px;
  padding-right: 26px;
  color: #424242;
  /* background-color: lightblue; */
}

/* 我的订单表头CSS END */

/* 订单列表CSS */
.order .content ul .product-list {
  height: 85px;
  padding: 15px 26px 15px 0;
  border-top: 1px solid #e0e0e0;
  /* background-color: pink; */
}

.order .content ul .pro-img {
  float: left;
  height: 85px;
  width: 85px;
  padding-left: 80px; /*原来80px*/
  /* background-color: red; */
}

.order .content ul .pro-img img {
  height: 80px;
  width: 80px;
}

.order .content ul .pro-name {
  float: left;
  width: 280px; /*原380px*/
  /* background-color: purple; */
  text-align: center;
}

.order .content ul .pro-name a {
  color: #424242;
}

.order .content ul .pro-name a:hover {
  color: #ff6700;
}

.order .content ul .pro-price {
  float: left;
  width: 150px;
  padding-right: 18px;
  text-align: center;
  /* background-color: green; */
}

.order .content ul .pro-num {
  float: left;
  width: 150px;
  text-align: center;
}

.order .content ul .pro-total {
  float: left;
  width: 150px;
  padding-right: 0px;
  text-align: center;
  /* background-color: yellow; */
}

.order .content ul .pro-status {
  float: left;
  width: 150px;
  padding-right: 0px;
  text-align: center;
  /* background-color: pink; */
}

.order .content ul .pro-delete {
  float: left;
  width: 100px;
  padding-right: 0px;
  text-align: center;
  /* background-color: lightgreen; */
}

.order .content ul .pro-total-in {
  color: #ff6700;
}

.order .order-bar {
  width: 1185px;
  padding: 0 20px;
  border-top: 1px solid #ff6700;
  height: 50px;
  line-height: 50px;
  background-color: #fff;
}

.order .order-bar .order-bar-left {
  float: left;
}

.order .order-bar .order-bar-left .order-total {
  color: #757575;
}

.order .order-bar .order-bar-left .order-total-num {
  color: #ff6700;
}

.order .order-bar .order-bar-right {
  float: right;
}

.order .order-bar .order-bar-right .total-price-title {
  color: #ff6700;
  font-size: 14px;
}

.order .order-bar .order-bar-right .total-price {
  color: #ff6700;
  font-size: 30px;
}

/* 订单列表CSS END */

/* 订单为空的时候显示的内容CSS */
.order .order-empty {
  width: 1225px;
  margin: 0 auto;
}

.order .order-empty .empty {
  height: 300px;
  padding: 0 0 130px 558px;
  margin: 65px 0 0;
  background: url(../assets/imgs/cart-empty.png) no-repeat 124px 0;
  color: #b0b0b0;
  overflow: hidden;
}

.order .order-empty .empty h2 {
  margin: 70px 0 15px;
  font-size: 36px;
}

.order .order-empty .empty p {
  margin: 0 0 20px;
  font-size: 20px;
}

.goods .main .pagination {
  height: 50px;
  text-align: center;
}

/* 订单为空的时候显示的内容CSS END */
</style>
